package com.jmu.medicineknows.filter;

import com.alibaba.fastjson.JSONObject;
import com.jmu.medicineknows.config.RedisCache;
import com.jmu.medicineknows.entity.LoginUser;
import com.jmu.medicineknows.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Console;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author Administrator
 */
@Component
@SuppressWarnings("all")
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    public static final String PV_KEY = "pv";
    public static final String PV_PREFIX = "pv:";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String token = request.getHeader("token");
        String requestURI = request.getRequestURI();
        String requestPrefix = requestURI.split("/")[1];
        if (requestURI.equals(request.getContextPath() + "/permission/LoginInfo")) {
            token = "";
        }
        if(requestURI.equals("/drug/list") ||
                requestPrefix.equals("news")){
            String key = PV_PREFIX + sdf.format(new Date());
            if(!redisCache.existsKey(PV_KEY)){
                Map <String,Integer> map = new HashMap<>();
                map.put(key, 1);
                map.put("totalPv",1);
                redisCache.setCacheMap(PV_KEY,map);
            } else {
                Map<String, Integer> pvMap = redisCache.getCacheMap(PV_KEY);
                if (pvMap.containsKey(key)) {
                    pvMap.put(key,pvMap.get(key)+1);
                    pvMap.put("totalPv",pvMap.get("totalPv")+1);
                } else {
                    pvMap.put(key,1);
                    pvMap.put("totalPv",1);
                }
                redisCache.setCacheMap(PV_KEY,pvMap);
            }
            filterChain.doFilter(request,response);
            return;
        }
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
            return;
        }
        String id;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            id = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        String key = "login:"+id;
        LoginUser loginUser = JSONObject.toJavaObject(redisCache.getCacheObject(key),LoginUser.class);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
